import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import Upload from 'rc-upload';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { expertAdd, expertUpdate, expertDelete } from '../../services/api';
import { getArrFromObj, getToken, getCurrent } from '../../utils/utils';
import config from '../../common/config';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './expertList.less';

import uploadPng from '../../assets/upload.png';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const PAGE_STATUS_MAP = {
  '0': '无效',
  '1': '有效',
};

const PAGE_STATUS_ARR = getArrFromObj(PAGE_STATUS_MAP);

const PAGE_CATEGORY_MAP = {
  1: '新闻动态',
  2: '政策资讯',
  3: '知产干货',
  4: '关于我们',
};

const PAGE_CATEGORY_ARR = getArrFromObj(PAGE_CATEGORY_MAP);

const STATUS_MAP = {
  0: '暂存',
  1: '待审核',
  2: '审核通过',
  3: '审核不通过',
};

const STATUS_ARR = getArrFromObj(STATUS_MAP);

const PROJECT_TYPE_MAP = {
  0: '非战略咨询类',
  1: '战略咨询类',
};

const PROJECT_TYPE_ARR = getArrFromObj(PROJECT_TYPE_MAP);

const PAGE_SIZE = 10;

@connect(({ expertList, loading }) => {
  return {
    expertList,
    loading: loading.models.expertList,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    id: null,

    title: null,
    status: '1',
    category: '1',
    author: getCurrent().username,

    pcTitle: null,
    pcKeywords: null,
    pcDesc: null,
    mobileTitle: null,
    mobileKeywords: null,
    mobileDesc: null,
    content: '',

    imgOptions: {},
    coverUrl: null,
  };

  componentDidMount() {
    this.getImgOptions();
    this.init();
  }

  getImgOptions() {
    const token = getToken();

    const imgOptions = {
      action: config.serveraddress + '/upload/putObject?dataType=0',
      data: { dataType: 0 },
      headers: {
        Authorization: 'Bearer ' + token,
      },
      multiple: false,
      beforeUpload(file) {
        console.log('beforeUpload', file.name);
      },
      onStart: file => {
        console.log('onStart', file.name);
      },
      onProgress(step, file) {},
    };

    this.setState({
      imgOptions,
    });
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'expertList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'expertList/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'expertList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime) {
        fieldsValue.startTime =
          moment(fieldsValue.createTime[0]).format('YYYY-MM-DD') + 'T00:00:00Z';
        fieldsValue.endTime = moment(fieldsValue.createTime[1]).format('YYYY-MM-DD') + 'T23:59:59Z';
      }

      delete fieldsValue['createTime'];

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      dispatch({
        type: 'expertList/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      levelRule: '',
      name: '',
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const { expertName, unitsName, userName, password } = this.state;
    if (!expertName) {
      return message.error('请填写专家名称');
    }

    if (!unitsName) {
      return message.error('请填写单位名称');
    }

    if (!userName) {
      return message.error('请填写用户名');
    }

    if (!password) {
      return message.error('请填写登录密码');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const { id, expertName, unitsName, userName, password } = this.state;

    let response = {};
    if (id) {
      const params = { id, expertName, unitsName, password };
      response = await expertUpdate(params);
    } else {
      const params = { expertName, unitsName, userName, password };
      response = await expertAdd(params);
    }

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      this.init();
    } else {
      message.error(response.message);
    }
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleEdit(item) {
    this.setState({
      ...item,
      content: BraftEditor.createEditorState(item.content),
      modalVisible: true,
    });
  }

  async handleDelete(item) {
    const params = { id: item.id };
    const response = await expertDelete(params);
    if (response.code === 200) {
      this.init();
    } else {
      message.error(response.message);
    }
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('expertName')(<Input placeholder="专家姓名" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('unitsName')(<Input placeholder="所属单位" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('userName')(<Input placeholder="用户名" />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24} style={{ padding: '0' }}>
            <span style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                type="primary"
                onClick={this.handleShowModal.bind(this)}
                style={{ marginLeft: 5 }}
              >
                新增
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleEditorChange = editorState => {
    this.setState({
      content: editorState,
    });
  };

  uploadSuccess(res, field) {
    this.setState({
      [field]: res.data,
    });
  }

  uploadError(res, field) {
    debugger;
  }

  render() {
    let { expertList: { data }, loading } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { selectedRows, modalVisible, imgOptions, coverUrl } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '专家姓名',
        ellipsis: true,
        width: 100,
        dataIndex: 'expertName',
      },
      {
        title: '所属单位',
        dataIndex: 'unitsName',
      },
      {
        title: '用户名',
        dataIndex: 'userName',
      },
      {
        title: '操作',
        dataIndex: '',
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleEdit.bind(this, item)}>
              编辑
            </a>{' '}
            <a href="javascript:;" onClick={this.handleDelete.bind(this, item)}>
              删除
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="专家列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          maskClosable={false}
          width="40%"
          title="新增专家"
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="专家姓名">
                  <Input
                    style={{ width: '300px' }}
                    value={this.state.expertName}
                    onChange={this.handleOnchange.bind(this, 'expertName')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="所属单位">
                  <Input
                    style={{ width: '300px' }}
                    value={this.state.unitsName}
                    onChange={this.handleOnchange.bind(this, 'unitsName')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="用 户 名">
                  <Input
                    disabled={!!this.state.id}
                    style={{ width: '300px' }}
                    value={this.state.userName}
                    onChange={this.handleOnchange.bind(this, 'userName')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>
          <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
            <Col span={24}>
              <DescriptionList size="large" title="" style={{ width: '100%', margin: '10px' }}>
                <Description term="登录密码">
                  <Input
                    style={{ width: '300px' }}
                    value={this.state.password}
                    onChange={this.handleOnchange.bind(this, 'password')}
                  />
                </Description>
              </DescriptionList>
            </Col>
          </Row>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
